var express = require('express');
var path = require('path');
var fs = require("fs");
var router = express.Router();
const md5 = require('blueimp-md5')
const models = require('../db/models')
const UserModel = models.getModel('user')
const _filter = {'pwd': 0, '__v': 0} // 查询时过滤掉
const sms_util = require('../util/sms_util')
const users = {}
const ajax = require('../api/ajax')
var svgCaptcha = require('svg-captcha')
var formidable = require('../node_modules/formidable');//nodejs接收上传的图片主要是使用formidable模块，服务器是使用的express搭建。
/*
密码登陆
 */
router.post('/login_pwd', function (req, res) {
  const name = req.body.name||'abc'
  const pwd = md5(req.body.pwd||'123')
  const captcha = req.body.captcha.toLowerCase()
  console.log('/login_pwd', name, pwd, captcha, req.session)

  // 可以对用户名/密码格式进行检查, 如果非法, 返回提示信息
  console.log(captcha,captcha)
/*  if(captcha!==req.session.captcha) {
    return res.send({code: 1, msg: '验证码不正确'})
  }
  // 删除保存的验证码
  delete req.session.captcha */

  UserModel.findOne({name}, function (err, user) {
    if (user) {
      console.log('findUser', user)
      if (user.pwd !== pwd) {
        res.send({code: 1, msg: '用户名或密码不正确!'})
      } else {
        req.session.userid = user._id
        res.send({code: 0, data: {_id: user._id, name: user.name, phone: user.phone}})
      }
    } else {
      const userModel = new UserModel({name, pwd})
      userModel.save(function (err, user) {
        // 向浏览器端返回cookie(key=value)
        res.cookie('userid', user._id, {maxAge: 1000*60*60*24*7})
        req.session.userid = user._id
        const data = {_id: user._id, name: user.name}
        // 3.2. 返回数据(新的user)
        res.send({code: 0, data})
      })
    }
  })
})
//修改个人信息
router.post("/editUserInfo", function (req, res) {
     const { phone,img} = req.body
     // console.log( JSON.stringify(req.body),"userbidy---pre")
     const userid =req.session.userid
     // console.log( JSON.stringify(userid),"userid---pre")
   //  UserModel.create({phone:phone},function(err,docs){
   //  　　　　if(err){
   //             console.log('写入失败')
   //        }else{
   //  　　　　　　console.log('写入数据成功'+docs)   ///加上docs 是看看 写入的数据在数据库中长什么样
   //  　　　　　　res.redirect('/');    ////写入数据库中 重新加载一下
   //  　　　　}
   // })
   //存储数据
     const userModel = new UserModel({phone,img})
     userModel.save(function (err, user) {
         console.log(user,"user._id.editUserInfo")
       const data = {_id:userid,phone:user.phone,img:user.img}
       // res.cookie('userid',userid, {maxAge: 1000*60*60*24*7})
       // req.session.userid =data
       // console.log(user._id,"user._id.editUserInfo")
       // 3.2. 返回数据(新的user)
       res.send({code: 0, data})
     })
    
     console.log("=======================================")
     console.log(userModel,"userModel")
    //  const userid =JSON.stringify(req.session.userid) 
    // UserModel.create({phone:phone,img:img}).then((data) => {
    //     res.send({ err: 0, msg: 'addok', data: data})
    //     console.log(data,"===data===")
    // })
    // .catch((err) => {
    //     res.send({ err: -1, msg: err._message, data: null })
    // })
    
   // userModel.save(function (err, user) {
   //   res.send({code: 0, data: user})
   // })
})


//拦截请求，设置formidable的常规项 上传图片
router.post("/image",function (req,res) {
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    let mypath=path.resolve('public' ,"./upload", )
    console.log(mypath)
    // return  
    form.uploadDir = path.resolve('public' ,"./upload" )
    // form.uploadDir = path.join(__dirname + "/upload");
    form.keepExtensions = true;//保留后缀
    form.maxFieldsSize = 2 * 1024 * 1024;
     //处理图片
    form.parse(req, function (err, fields, files){
            console.log(typeof(files),"======");
            console.log(JSON.stringify(files.file.name),"======");
            // return
            var filename = files.file.name
            var nameArray = filename.split('.');
            var type = nameArray[nameArray.length - 1];
            var name = '';
            for (var i = 0; i < nameArray.length - 1; i++) {
                name = name + nameArray[i];
            }
            var date = new Date();
            var time = '_' + date.getFullYear() + "_" + date.getMonth() + "_" + date.getDay() + "_" + date.getHours() + "_" + date.getMinutes();
            var avatarName = name + time + '.' + type;
            var newPath = form.uploadDir + "/" + avatarName;
            console.log(JSON.stringify(path.resolve(newPath)),"======");
            fs.renameSync(files.file.path, newPath);  //重命名
            res.send({code: 0,data:"/upload/"+avatarName})
    })
});
router.get('/upload', function (req, res) {
    var readFile = require('./upload');
    res.send(readFile)
})
/*
一次性图形验证码
 */
router.get('/captcha', function (req, res) {
  var captcha = svgCaptcha.create({
    ignoreChars: '0o1l',
    noise: 2,
    color: true
  });
  req.session.captcha = captcha.text.toLowerCase();
  // console.log(req.session.captcha)
  /*res.type('svg');
  res.status(200).send(captcha.data);*/
  res.type('svg');
  res.send(captcha.data)
});

/*
发送验证码短信
*/
router.get('/sendcode', function (req, res, next) {
  //1. 获取请求参数数据
  var phone = req.query.phone;
  //2. 处理数据
  //生成验证码(6位随机数)
  var code = sms_util.randomCode(6);
  //发送给指定的手机号
  console.log(`向${phone}发送验证码短信: ${code}`);
  sms_util.sendCode(phone, code, function (success) {//success表示是否成功
    if (success) {
      users[phone] = code
      console.log('保存验证码: ', phone, code)
      res.send({"code": 0})
    } else {
      //3. 返回响应数据
      res.send({"code": 1, msg: '短信验证码发送失败'})
    }
  })
})

/*
短信登陆
*/
router.post('/login_sms', function (req, res, next) {
  var phone = req.body.phone;
  var code = req.body.code;
  // console.log('/login_sms', phone, code);
  if (users[phone] != code) {
    res.send({code: 1, msg: '手机号或验证码不正确'});
    return;
  }
  //删除保存的code
  delete users[phone];


  UserModel.findOne({phone}, function (err, user) {
    if (user) {
      req.session.userid = user._id
      res.send({code: 0, data: user})
    } else {
      //存储数据
      const userModel = new UserModel({phone})
      userModel.save(function (err, user) {
        req.session.userid = user._id
        res.send({code: 0, data: user})
      })
    }
  })

})

/*
根据sesion中的userid, 查询对应的user
 */
router.get('/userinfo', function (req, res) {
  // 取出userid
  const userid =req.session.userid
  // 查询
  console.log(userid,"user_id-info")
  // console.log(userid,'userid======')
  //   UserModel.find({_id: userid}, function (err, docs) {
  //   // 如果没有, 返回错误提示
  //   console.log(docs,'======')
  //   // if (!user) {
  //   //   // 清除浏览器保存的userid的cookie
  //   //   delete req.session.userid
  //   //   res.send({code: 1, msg: '请先登陆'})
  //   // } else {
  //   //         console.log(user)
  //   //   // 如果有, 返回user
  //   //   res.send({code: 0, data: user})
  //   // }
  // })
  UserModel.findOne({_id: userid}, function (err, user) {
    // 如果没有, 返回错误提示
    if (!user) {
      // 清除浏览器保存的userid的cookie
      delete req.session.userid
      res.send({code: 1, msg: '请先登陆'})
    } else {
        // console.log(user,'userid======')
      // 如果有, 返回user
      res.send({code: 0, data: user})
    }
  })
})


router.get('/logout', function (req, res) {
  // 清除浏览器保存的userid的cookie
  delete req.session.userid
  // 返回数据
  res.send({code: 0})
})

/*
根据经纬度获取位置详情
 */
router.get('/position/:geohash', function (req, res) {
  const {geohash} = req.params
  ajax(`http://cangdu.org:8001/v2/pois/${geohash}`)
    .then(data => {
      res.send({code: 0, data})
    })
})

/*
获取首页分类列表
 */
// router.get('/index_category', function (req, res) {
//   setTimeout(function () {
//     const data = require('../data/index_category.json')
//     res.send({code: 0, data})
//   }, 300)
// })
router.get('/index_category', function (req, res) {
  setTimeout(function () {
    const data = require('../data/swiper.json')
    res.send({code: 0, data})
  }, 300)
})
//附近房源
router.get('/near_house', function (req, res) {
  setTimeout(function () {
    const data = require('../data/nearHouse.json')
    res.send({code: 0, data})
  }, 300)
})

/*
根据经纬度获取商铺列表
?latitude=40.10038&longitude=116.36867
 */
router.get('/shops', function (req, res) {
  const latitude = req.query.latitude
  const longitude = req.query.longitude

  setTimeout(function () {
    const data = require('../data/shops.json')
    res.send({code: 0, data})
  }, 300)
})

router.get('/search_shops', function (req, res) {
  const {geohash, keyword} = req.query
  ajax('http://cangdu.org:8001/v4/restaurants', {
    'extras[]': 'restaurant_activity',
    geohash,
    keyword,
    type: 'search'
  }).then(data => {
    res.send({code: 0, data})
  })
})

module.exports = router;